<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\Radar\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\Radar\Contract\RadarContract;
use MoChat\Plugin\Radar\Contract\RadarRecordContract;

/**
 * 互动雷达- 数据详情.
 *
 * Class Show.
 * @Controller
 */
class ClickShow extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var RadarContract
     */
    protected $radarService;

    /**
     * @Inject
     * @var RadarRecordContract
     */
    protected $radarRecordService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/sidebar/radar/clickShow", methods="get")
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        // 参数验证
        $this->validated($this->request->all());
        // 接收参数
        $params['id'] = (int) $this->request->input('id');
        $params['type'] = (int) $this->request->input('type', 0);
        $params['contactId'] = (int) $this->request->input('contactId', 0);
        $params['employeeId'] = $user['id'];
        // 查询数据
        return $this->handleData($params);
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required | integer | min:0 | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => '活动ID 必填',
            'id.integer' => '活动ID 必需为整数',
            'id.min  ' => '活动ID 不可小于1',
        ];
    }

    private function handleData(array $params): array
    {
        $time = $params['type'] === 1 ? date('Y-m-d') : '';
        // 互动雷达点击信息
        $list = $this->radarRecordService->getRadarRecordsByRadarIdContactIdEmployeeIdCreatedAt($params['id'], $params['contactId'], $params['employeeId'], $time, ['created_at']);
        foreach ($list as $key => &$item) {
            $item['num'] = $key + 1;
        }
        unset($item);

        return $list;
    }
}
